<script setup>
import { updateRoomDetail } from '@/api/chat'
import useLocale from '@/composables/useLocale'
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import { computed, ref, watchEffect } from 'vue'
import { useStore } from 'vuex'

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
})
const emit = defineEmits(['update:modelValue'])

const store = useStore()
const popupRef = ref(null)
const roomDetail = computed(() => store.state.chat.roomDetail)
const newRoomName = ref(roomDetail.value?.roomName)
const { t } = useLocale()

watchEffect(() => {
    newRoomName.value = roomDetail.value?.roomName
})

watchEffect(() => {
    if (props.modelValue) {
        popupRef.value?.open()
    } else {
        popupRef.value?.close()
    }
})

function handleMaskClick() {
    emit('update:modelValue', false)
}

async function handleRename() {
    try {
        emit('update:modelValue', false)
        await updateRoomDetail({
            roomName: newRoomName.value,
            id: roomDetail.value.id,
        })
        store.dispatch('chat/updateRoomList')
    } catch (_) {
        /* empty */
    }
}
</script>

<template>
    <uni-popup ref="popupRef" type="center" @mask-click="handleMaskClick">
        <view
            class="w-[85vw] rounded-3xl bg-white px-5 py-7 text-base text-zinc-950 md:w-[60vw] lg:w-[45vw]"
        >
            <view class="relative">
                <view
                    class="absolute left-3 top-0 -translate-y-1/2 bg-white px-2 text-sm"
                >
                    {{ t('newName') }}
                </view>
                <input
                    v-model="newRoomName"
                    class="h-12 rounded border border-zinc-950 px-3 [border-style:solid]"
                    focus
                />
            </view>
            <view class="mt-3 flex justify-end gap-4">
                <view @click="emit('update:modelValue', false)">
                    {{ t('cancel') }}
                </view>
                <view @click="handleRename">{{ t('rename') }}</view>
            </view>
        </view>
    </uni-popup>
</template>
